package com.controller;/**
 * @program: SmbmsDemo
 * @description: 用户控制器
 * @author: Mr.Kang
 * @create: 2020-06-06 10:38
 **/

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.pojo.Role;
import com.pojo.User;
import com.service.RoleService;
import com.service.UserService;
import com.tools.Constants;
import com.tools.PageSupport;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author 康康真滴暖
 * @date 2020-06-06 10:38
 */
@Controller
public class UserController {

    @Resource
    private UserService userServices;
    @Resource
    private RoleService roleService;

    @RequestMapping(value = "Rolequery")
    public String Rolequery(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //查询用户列表
        String queryUserName = request.getParameter("queryname");
        String temp = request.getParameter("queryUserRole");
        String pageIndex = request.getParameter("pageIndex");
        int queryUserRole = 0;
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if(queryUserName == null){
            queryUserName = "";
        }
        if(temp != null && !temp.equals("")) {
            queryUserRole = Integer.parseInt(temp);
        }
        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                /* response.sendRedirect("error.jsp");*/
               return "redirect:/error";
            }
        }
        //总数量（表）
        int totalCount	= userServices.getUserCount(queryUserName,queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userServices.getUserList(queryUserName,queryUserRole,(currentPageNo-1)*pageSize, pageSize);
        request.setAttribute("userList", userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        request.setAttribute("roleList", roleList);
        request.setAttribute("queryUserName", queryUserName);
        request.setAttribute("queryUserRole", queryUserRole);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("currentPageNo", currentPageNo);
        /*  request.getRequestDispatcher("userlist.jsp").forward(request, response);*/
        return "userlist";
    }

    @RequestMapping(value = "delUser")
    @ResponseBody
    public String delUser(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String id = request.getParameter("uid");
        Integer delId = 0;
        try{
            delId = Integer.parseInt(id);
        }catch (Exception e) {
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(delId <= 0){
            resultMap.put("delResult", "notexist");
        }else{
            int count=userServices.deleteUserById(delId);
            if(count>0){
                resultMap.put("delResult", "true");
            }else{
                resultMap.put("delResult", "false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }

    @RequestMapping(value = "xiugai")
    public String xiugai(){
        return "pwdmodify";
    }

    @RequestMapping(value = "updatePwd")
    public String updatePwd(HttpServletRequest request, HttpServletResponse response)
            throws Exception{
        Object o = request.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = request.getParameter("newpassword");
        int count;
        if(o != null && !StringUtils.isNullOrEmpty(newpassword)){
            /*	UserService userService = new UserServiceImpl();*/
            count = userServices.updatePwd(((User)o).getId(),newpassword);
            if(count>0){
                request.setAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
                request.getSession().removeAttribute(Constants.USER_SESSION);//session注销
            }else{
                request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
            }
        }else{
            request.setAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
        }
        return "pwdmodify";
    }

    @RequestMapping(value = "getPwdByUserId")
    public void getPwdByUserId(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Object o = request.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = request.getParameter("oldpassword");
        Map<String, String> resultMap = new HashMap<String, String>();

        if(null == o ){//session过期
            resultMap.put("result", "sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//旧密码输入为空
            resultMap.put("result", "error");
        }else{
            String sessionPwd = ((User)o).getUserPassword();
            if(oldpassword.equals(sessionPwd)){
                resultMap.put("result", "true");
            }else{//旧密码输入不正确
                resultMap.put("result", "false");
            }
        }
        response.setContentType("application/json");
        PrintWriter outPrintWriter = response.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    @RequestMapping(value = "Usermodify")
    public String modify(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String id = request.getParameter("uid");
        String userName = request.getParameter("userName");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        int count=userServices.modify(user);
        if(count>0){
            return "redirect:/Rolequery";
        }else{
            return "usermodify";
        }
    }

    @RequestMapping(value = "getUserById")
    public String getUserById(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String id = request.getParameter("uid");
        String method = request.getParameter("method");
        String url;
        if (method.equals("view")){
            url="userview";
        }else {
            url="usermodify";
        }
        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            User user = userServices.getUserById(id);
            request.setAttribute("user", user);
            return url;
        }
        return null;
    }

    @RequestMapping(value = "userCodeExist")
    @ResponseBody
    public String userCodeExist(HttpServletRequest request, HttpServletResponse response){
        //判断用户账号是否可用
        String userCode = request.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        }else{
            User user = userServices.selectUserCodeExist(userCode);
            if(null != user){
                resultMap.put("userCode","exist");
            }else{
                resultMap.put("userCode", "notexist");
            }
        }
        response.setContentType("application/json");
        return JSONArray.toJSONString(resultMap);

    }
    @RequestMapping("getRoleList")
    @ResponseBody
    public String getRoleList(HttpServletResponse response){
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        return JSONArray.toJSONString(roleList);
    }

    @RequestMapping(value = "addDemo")
    public String addDemo(){
        return "useradd";
    }

    @RequestMapping(value = "Useradd")
    public String Useradd(HttpServletRequest request, HttpServletResponse response) throws Exception{
        System.out.println("add()================");
        String userCode = request.getParameter("userCode");
        String userName = request.getParameter("userName");
        String userPassword = request.getParameter("userPassword");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String userRole = request.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)request.getSession().getAttribute(Constants.USER_SESSION)).getId());
        int count=userServices.add(user);
        try {
            if(count>0){
                return "redirect:/Rolequery";
            }else{
                return "useradd";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "useradd";
    }
}
